/* eslint-disable react-hooks/exhaustive-deps */
// {
// car001:{name:'本田，price：100}
// }
import React, { memo, useCallback } from "react"
import { createContext, useContext, useState } from "react"
const CarsContext=createContext()
const Car=({car,id,incr,decr})=>{
    console.log('car',id)
    const {cars}=useContext(CarsContext)
    return<div>
        <p>名称:{car.name}</p>
        <p>价格:{car.price}</p>
        <button className="btn btn-primary" onClick={()=>incr(cars)(id)} >增加</button>
        <button className="btn btn-primary" onClick={()=>decr(cars)(id)}>减少</button>
    </div>
}

const Cars=()=>{
    console.log('cars')
 const{cars,incr,decr}= useContext(CarsContext)
    return<div>
            {Object.keys(cars).map((id)=><Car id={id} key={id} car={cars[id]} incr={incr} decr={decr} />)}
    </div>
}

const ProductList=memo(()=>{
    console.log('ProductList')  

    return<div>
    <h3>汽车:</h3>
    <Cars  />
    </div>
  
})
const CarsDemo=()=>{
    console.log('CarsDemo')

    const[state,setState]=useState({
        car001:{name:'本田',price:100},
        car002:{name:'宝马',price:200},
        car003:{name:'奔驰',price:300},
    })
    const incrPrice=useCallback((state)=>(carId)=>{
        
         setState({...state,[carId]:{...state[carId],price:state[carId].price+1
        }})
    },[setState])
    const decrPrice=useCallback((state)=>(carId)=>{
        setState({...state,[carId]:{...state[carId],price:state[carId].price-1
       }})
   },[setState])
return(
    <div>
        <CarsContext.Provider value={{cars:state,incr:incrPrice,decr:decrPrice}}>
          <h2>产品展厅</h2>
        <ProductList  />   
        </CarsContext.Provider>
       
    </div>
)
}
    export default CarsDemo